package com.miplus.ccrm.core.service;

import com.miplus.ccrm.common.CmdResVo;
import com.miplus.ccrm.common.EnumRCode;
import com.miplus.ccrm.common.JPubUtils;
import com.miplus.ccrm.common.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class ExportService {

    private String GetCellValue(HashMap<String,Object> map,String key)
    {
        String ret="";
        for(String mkey : map.keySet()){
            if(JPubUtils.IsEqual(mkey,key)){
                Object obj=map.get(mkey);
                if(obj instanceof Date){
                    ret=JPubUtils.DTimeToString(obj);
                }else {
                    ret = JPubUtils.ObjectToString(obj);
                }
                break;
            }
        }
        return ret;
    }

    public CmdResVo ToExcel(HttpServletResponse response,ArrayList<HashMap<?, ?>> arrList,List<String> colids,List<String> colnames,String outfilename,String $usrid)
    {
        int ret=arrList.size();
        SimpleDateFormat sdf=new SimpleDateFormat("yyMMddHHmmss");
        String batchid= $usrid + "." + sdf.format(new Date());

        String retfilename=outfilename;
        if(JPubUtils.IsEmpty(retfilename)){
            retfilename=sdf.format(new Date())+".xlsx";
        }
        log.info("ToExcel:count={},batchid={},expfilename={}",ret,batchid,retfilename);

        try{
            log.info("ToExcel:colids={},colnames={}",colids,colnames);

            Workbook workbook = new XSSFWorkbook();
            //在工作簿中创建一张表sheet
            Sheet sheet = workbook.createSheet("sheet1");
            Row row;
            row = sheet.createRow(0);
            for(int j=0;j<colnames.size();j++){
                row.createCell(j).setCellValue(colnames.get(j));
            }
            for (int i = 0; i < arrList.size(); i++) {
                row = sheet.createRow(i + 1);
                HashMap map=arrList.get(i);
                for(int j=0;j<colids.size();j++){
                    row.createCell(j).setCellValue(GetCellValue(map,colids.get(j)));
                }
            }
            arrList.clear();
            colids.clear();
            colnames.clear();

            log.info("ToExcel:create excel:{}",retfilename);
            //需要通过response给前端数据流，设置对应的response
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(retfilename,"utf-8"));
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();
            log.info("ToExcel:create excel Ok.");
        } catch (IOException e) {
            log.warn("ToExcel.Err",e);
            throw new ServiceException(EnumRCode.ExcelErr.value, e.getMessage());
        }

        return new CmdResVo(ret,batchid);
    }

    public Workbook AddExcel(Workbook workbook,String sheet1name,ArrayList<HashMap<?, ?>> arrList,List<String> colnames)
    {
        log.info("AddExcel:sheet={},count={}",sheet1name,arrList.size());

        Sheet sheet = workbook.createSheet(sheet1name);
        Row row=sheet.createRow(0);
        for(int j=0;j<colnames.size();j++){
            row.createCell(j).setCellValue(colnames.get(j));
        }
        for (int i = 0; i < arrList.size(); i++) {
            row = sheet.createRow(i + 1);
            HashMap map=arrList.get(i);
            for(int j=0;j<colnames.size();j++){
                row.createCell(j).setCellValue(GetCellValue(map,colnames.get(j)));
            }
        }

        log.info("AddExcel.Done");

        return workbook;
    }

    public CmdResVo fiCaseToExcel(HttpServletResponse response,String outfilename,String $usrid,ArrayList<HashMap<?, ?>> accList,
                                  ArrayList<HashMap<?, ?>> phnList,ArrayList<HashMap<?, ?>> addrList,ArrayList<HashMap<?, ?>> cardList,
                                  ArrayList<HashMap<?, ?>> amortList)
    {
        int ret=accList.size();
        SimpleDateFormat sdf=new SimpleDateFormat("yyMMddHHmmss");
        String batchid= $usrid + "." + sdf.format(new Date());

        String retfilename=outfilename;
        if(JPubUtils.IsEmpty(retfilename)){
            retfilename=sdf.format(new Date())+".xlsx";
        }

        log.info("fiCaseToExcel:batchid={},outfilename={},acccount={}",batchid,retfilename,ret);

        try{
            Workbook workbook = new XSSFWorkbook();

            List<String> colnames=Arrays.asList("客户编号","案件编号","账户编号","姓名","产品类型","卡号","证件号","固定额度","逾期期数","账户状态","账单日","还款日","总欠款",
                    "总欠款本金","总欠款利息","总欠款费用","已出账单欠款","最低还款额","逾期金额","已出账单本金","已出账单利息","已出账单费用","剩余分期付款本金(总额)",
                    "剩余分期未还费用(总额)","自带标签","系统属性标签");
            AddExcel(workbook,"账户信息",accList,colnames);

            colnames=Arrays.asList("账户编号","卡号","证件号","联系人姓名","关系","来源","电话类型","联系人电话");
            AddExcel(workbook,"电话簿",phnList,colnames);

            colnames=Arrays.asList("账户编号","卡号","证件号","地址来源","地址类型","省市区","详细地址");
            AddExcel(workbook,"地址簿",addrList,colnames);

            colnames=Arrays.asList("账户编号","账户类型","卡号","证件号","卡片状态","激活日期","发卡日期");
            AddExcel(workbook,"卡片信息",cardList,colnames);

            colnames=Arrays.asList("客户名","卡号","证件号","分期总金额","分期期数","首期还款日","首期还款金额","每期还款日","每期还款金额","累计实际还款","实际剩余金额","状态");
            AddExcel(workbook,"协商分期",amortList,colnames);

            accList.clear();
            phnList.clear();
            addrList.clear();
            cardList.clear();
            amortList.clear();

            log.info("fiCaseToExcel:create excel:{}",retfilename);
            //需要通过response给前端数据流，设置对应的response
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(retfilename,"utf-8"));
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();
            log.info("fiCaseToExcel:create excel Ok.");
        } catch (IOException e) {
            log.warn("fiCaseToExcel.Err",e);
            throw new ServiceException(EnumRCode.ExcelErr.value, e.getMessage());
        }

        return new CmdResVo(ret,batchid);
    }
}
